package com.ddone.service.impl;

import com.ddone.bean.Order;
import com.ddone.feign.StockClient;
import com.ddone.mapper.OrderMapper;
import com.ddone.service.OrderService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.HttpClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.Date;
import java.util.UUID;

/**
 * @author ddone
 * @date 2024/4/6-15:27
 */
@Slf4j
@Service
public class OrderServiceImpl implements OrderService {

    @Resource
    private OrderMapper orderMapper;

    @Resource
    private HttpClient httpClient;

    @Resource
    private RestTemplate restTemplate;

    @Resource
    private StockClient stockClient;

    @HystrixCommand(fallbackMethod = "saveOrderFallBack")
    @Override
    public Boolean saveOrder(String userId, String productId, Integer count) {
        Order order = Order.builder()
                .userId(userId)
                .productId(productId)
                .orderSn(UUID.randomUUID().toString().replace("-", ""))
                .count(count)
                .money(1000)
                .createTime(new Date())
                .build();
        orderMapper.save(order);
        // 更新库存
        String url = "http://spring-cloud-stock/stock/"+productId+"/"+count;
        // 使用 restTemplate之后 不能直接写IP和端口 否则负载均衡不识别
        // HttpGet httpGet = new HttpGet(url);
        // try {
        //     HttpResponse response = httpClient.execute(httpGet);
        //     boolean result = Boolean.parseBoolean(EntityUtils.toString(response.getEntity()));
        //     System.out.println("库存更新结果: "+result);
        // } catch (IOException e) {
        //     e.printStackTrace();
        // }
        // Boolean result = restTemplate.getForObject(url, Boolean.class, productId, count);
        Boolean result = stockClient.updateStock(productId, count);
        System.out.println("库存更新结果: "+result);
        return order.getId() != null;
    }



    public Boolean saveOrderFallBack(String userId, String productId, Integer count) {
        log.warn("启用降级方案-saveOrderFallback： userId:"+userId+" , " +
                "productId："+productId+" , count:"+count);
        return false;
    }
}
